//
//  MKWParserService.m
//  MilkyWayReader
//
//  Created by Louis CHU on 03/04/12.
//  Copyright (c) 2012 Milky Way Mobile. All rights reserved.
//

#import "MKWParserService.h"
#include <libxml2/libxml/HTMLparser.h>
#include <libxml2/libxml/HTMLtree.h>
static inline htmlNodePtr htmlFindNdeWithName (htmlNodePtr node, xmlChar *name) {
    // Look for nodes named `name` among the siblings of `node`
    for (; node != NULL; node = node->next) {
        if (node->type == XML_ELEMENT_NODE && xmlStrEqual(node->name, name)) {
            return node;
        }
    }
    
    return NULL;
}

static inline NSString *NSStringFromXMLString(const xmlChar *xmlString) {
    return [[NSString alloc] initWithBytes:xmlString length:xmlStrlen(xmlString) encoding:NSUTF8StringEncoding];
}

@implementation MKWParserService
+ (NSDictionary *) htmlParser: (NSData *) data_
{
    NSString * pathFile = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"];
    NSData * data = [NSData dataWithContentsOfFile:pathFile];
    if (data.length > 0) {
        htmlDocPtr document = htmlReadMemory(data.bytes, data.length, NULL, NULL, 0);
        if (document != NULL) {
            htmlNodePtr htmlNode =  htmlFindNdeWithName( xmlDocGetRootElement(document), BAD_CAST"html");
            NSLog(@"%@",NSStringFromXMLString(htmlNode->children->children->children->content) );
             NSLog(@"%@",NSStringFromXMLString(htmlNode->children->name) );
        }
    }
    
    return nil;
}
@end
